package com.cloud.picture.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.picture.annotation.AuthCheck;
import com.cloud.picture.api.aliyunai.AliYunAiApi;
import com.cloud.picture.api.aliyunai.model.create.CreatePaintingTaskRequest;
import com.cloud.picture.api.aliyunai.model.create.CreatePaintingTaskResponse;
import com.cloud.picture.api.aliyunai.model.create.GetPaintingTaskResponse;
import com.cloud.picture.api.aliyunai.model.outpainting.CreateOutPaintingTaskResponse;
import com.cloud.picture.api.aliyunai.model.outpainting.GetOutPaintingTaskResponse;
import com.cloud.picture.common.BaseResponse;
import com.cloud.picture.constant.UserConstants;
import com.cloud.picture.exception.BusinessException;
import com.cloud.picture.model.dto.DeleteRequest;
import com.cloud.picture.model.dto.picture.*;
import com.cloud.picture.model.entity.Picture;
import com.cloud.picture.model.entity.PictureLike;
import com.cloud.picture.model.entity.Space;
import com.cloud.picture.model.entity.User;
import com.cloud.picture.model.enums.ErrorCodeEnum;
import com.cloud.picture.model.enums.PictureReviewStatusEnum;
import com.cloud.picture.model.enums.UserRoleEnum;
import com.cloud.picture.model.vo.PictureTagCategoryVO;
import com.cloud.picture.model.vo.PictureVO;
import com.cloud.picture.service.PictureLikeService;
import com.cloud.picture.service.PictureService;
import com.cloud.picture.service.SpaceService;
import com.cloud.picture.service.UserService;
import com.cloud.picture.utils.ResultUtils;
import com.cloud.picture.utils.ThrowUtils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author syf
 */
@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private PictureLikeService pictureLikeService;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 构造本地缓存
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();

    /**
     * 获取点赞图片列表
     */
    @PostMapping("/likes/list")
    @ApiOperation(value = "获取点赞图片列表")
    public BaseResponse<Page<PictureVO>> getPictureLike(@RequestBody PictureLikeListRequest pictureLikeRequest) {
        ThrowUtils.throwIf(pictureLikeRequest == null, ErrorCodeEnum.PARAMS_ERROR);

        // 获取分页参数（使用请求参数覆盖默认值）
        long current = pictureLikeRequest.getCurrent();
        long size = pictureLikeRequest.getPageSize();
        QueryWrapper<PictureLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", pictureLikeRequest.getUserId());
        Page<PictureLike> pictureVOPage = pictureLikeService.page(new Page<>(current, size), queryWrapper);
        List<Long> pictureIdList = pictureVOPage.getRecords().stream().map(PictureLike::getPictureId).collect(Collectors.toList());
        ThrowUtils.throwIf(pictureIdList.isEmpty(), ErrorCodeEnum.NOT_FOUND_ERROR);

        // 查询点赞记录对应的图片
        Page<PictureVO> resultPage = pictureService.getLikedPictures(pictureIdList, current, size);
        ThrowUtils.throwIf(CollectionUtils.isEmpty(resultPage.getRecords()),
            ErrorCodeEnum.NOT_FOUND_ERROR, "未找到点赞图片");
        
        return ResultUtils.success(resultPage);
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片")
    @ApiOperationSupport(order = 1)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile file,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureUploadWithUserRequest pictureUploadWithUserRequest = new PictureUploadWithUserRequest();
        BeanUtils.copyProperties(pictureUploadRequest, pictureUploadWithUserRequest);
        pictureUploadWithUserRequest.setLoginUser(loginUser);
        PictureVO pictureVO = pictureService.uploadPicture(file, pictureUploadWithUserRequest);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片
     */
    @PostMapping("/upload/url")
    @ApiOperation(value = "通过 URL 上传图片")
    @ApiOperationSupport(order = 1)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest.toPictureUploadWithUserRequest(loginUser));
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除图片")
    @ApiOperationSupport(order = 2)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCodeEnum.PARAMS_ERROR);
        return ResultUtils.success(pictureService.deletePicture(deleteRequest.getId(), request));
    }

    /**
     * 更新图片
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstants.ADMIN_ROLE)
    @ApiOperation(value = "更新图片")
    @ApiOperationSupport(order = 3)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest updateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(updateRequest == null, ErrorCodeEnum.PARAMS_ERROR);
        boolean res = pictureService.updatePicture(updateRequest, request);
        return ResultUtils.success(res);
    }

    /**
     * 获取图片
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstants.ADMIN_ROLE)
    @ApiOperation(value = "根据id获取图片")
    @ApiOperationSupport(order = 4)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCodeEnum.PARAMS_ERROR);
        // 查询
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        return ResultUtils.success(picture);
    }

    /**
     * 获取图片
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据id获取脱敏的图片")
    @ApiOperationSupport(order = 5)
    public BaseResponse<PictureVO> getPictureVoById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCodeEnum.PARAMS_ERROR);
        // 查询
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            User loginUser = userService.getLoginUser(request);
            pictureService.checkPictureAuth(loginUser, picture);
        }
        return ResultUtils.success(pictureService.getPictureVO(picture, request));
    }

    /**
     * 分页获取图片列表
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstants.ADMIN_ROLE)
    @ApiOperation(value = "分页获取图片列表")
    @ApiOperationSupport(order = 6)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        // 查询
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(queryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取脱敏图片列表")
    @ApiOperationSupport(order = 7)
    public BaseResponse<Page<PictureVO>> listPictureVoByPage(@RequestBody PictureQueryRequest queryRequest, HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        // 空间权限校验
        Long spaceId = queryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户只能看到审核过的公开信息
            User loginUser = userService.getLoginUser(request);
            if (loginUser == null || !loginUser.getUserRole().equals(UserRoleEnum.ADMIN.getValue()))
            {
                queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            }
            queryRequest.setNullSpaceId(true);
        } else {
            // 私有
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCodeEnum.NOT_FOUND_ERROR);
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR);
            }
        }
        // 查询
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(queryRequest));
        return ResultUtils.success(pictureService.getPictureVoPage(picturePage, request));
    }

    @PostMapping("/list/page/vo/cache")
    @ApiOperation(value = "分页获取脱敏图片列表(带缓存)")
    @ApiOperationSupport(order = 7)
    public BaseResponse<Page<PictureVO>> listPictureVoByPageWithCache(@RequestBody PictureQueryRequest queryRequest, HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        ThrowUtils.throwIf(size > 20, ErrorCodeEnum.PARAMS_ERROR);
        // 缓存公共区域图片
        queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        // 构建redis
        String queryCondition = JSONUtil.toJsonStr(queryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = "cloudPicture:listPictureVOByPage:" + hashKey;
        // 查询缓存
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        String cachedValue = valueOps.get(redisKey);
        // 缓存命中
        if (cachedValue != null) {
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(queryRequest));
        // 获取封装类
        Page<PictureVO> pictureVoPage = pictureService.getPictureVoPage(picturePage, request);

        // 存入缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVoPage);
        // 5 - 10 分钟随机过期，防止雪崩
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        valueOps.set(redisKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);

        return ResultUtils.success(pictureVoPage);
    }

    /**
     * 编辑（用户）
     */
    @PostMapping("/edit")
    @ApiOperation(value = "编辑图片")
    @ApiOperationSupport(order = 8)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest editRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(editRequest == null || editRequest.getId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        Picture picture = new Picture();
        BeanUtils.copyProperties(editRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(editRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 校验
        pictureService.validPicture(picture);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = editRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 权限
        pictureService.checkPictureAuth(loginUser, oldPicture);
        // 审核
        pictureService.fillReviewParams(picture, loginUser);
        // 更新
        boolean res = pictureService.updateById(picture);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取标签分类
     */
    @GetMapping("/tag_category")
    @ApiOperation(value = "获取标签分类")
    @ApiOperationSupport(order = 9)
    public BaseResponse<PictureTagCategoryVO> listPictureTagCategory() {
        PictureTagCategoryVO pictureTagCategoryVO = new PictureTagCategoryVO();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategoryVO.setTagList(tagList);
        pictureTagCategoryVO.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategoryVO);
    }

    /**
     * 图片审核
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstants.ADMIN_ROLE)
    @ApiOperation(value = "图片审核")
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCodeEnum.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量抓取图片
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstants.ADMIN_ROLE)
    @ApiOperation(value = "批量抓取图片")
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCodeEnum.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 图片点赞
     */
    @PostMapping("/like")
    @ApiOperation(value = "图片点赞")
    public BaseResponse<Boolean> likePicture(@RequestBody PictureLikeRequest pictureLikeRequest) {
        // 校验
        ThrowUtils.throwIf(pictureLikeRequest == null, ErrorCodeEnum.PARAMS_ERROR);
        boolean res = pictureService.likePicture(pictureLikeRequest);
        return ResultUtils.success(res);
    }

    /**
     * 批量修改图片信息
     * @param pictureEditByBatchRequest 修改图片信息
     * @return 是否修改成功
     */
    @PostMapping("/edit/batch")
    @ApiOperation(value = "批量修改图片信息")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
         ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCodeEnum.PARAMS_ERROR);
         User loginUser = userService.getLoginUser(request);
         pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
         return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     * @param createPictureOutPaintingTaskRequest 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @ApiOperation(value = "AI 扩图")
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask (
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 创建 AI 绘画任务
     * @param createPaintingTaskRequest 创建 AI 绘画任务
     * @param request 会话
     * @return 绘画任务结果
     */
    @PostMapping("/painting/create_task")
    @ApiOperation(value = "AI 绘画")
    public BaseResponse<CreatePaintingTaskResponse> createPicturePaintingTask (
            @RequestBody CreatePaintingTaskRequest createPaintingTaskRequest,
            HttpServletRequest request) {
        return null;
    }

    /**
     * 查询 AI 扩图任务
     * @param taskId 任务ID
     */
    @GetMapping("/out_painting/get_task")
    @ApiOperation(value = "查询 AI 扩图任务")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

    /**
     * 查询 AI 绘画任务
     * @param taskId 任务ID
     * @return 绘画任务结果
     */
    @GetMapping("/painting/get_task")
    @ApiOperation(value = "查询 AI 绘画任务")
    public BaseResponse<GetPaintingTaskResponse> getPicturePaintingTask(String taskId) {
        return null;
    }
}
